<template>
  <a-modal v-model:visible="visible" title="修改用户" :on-before-ok="confirm">
    <a-row justify="center">
      <a-form ref="formRef" :model="form" size="medium" auto-label-width :style="{ width: 'auto' }">
        <a-form-item field="nickname" label="用户昵称" :rules="rules.name">
          <a-input v-model="form.nickname" placeholder="请输入用户昵称" style="width: 300px" />
        </a-form-item>
        <a-form-item field="remarks" label="用户备注">
          <a-input v-model="form.remarks" placeholder="请输入用户备注" style="width: 300px" />
        </a-form-item>
        <a-form-item field="headimage" label="用户头像">
          <a-upload
            action="/"
            :fileList="file ? [file] : []"
            :show-file-list="false"
            :auto-upload="false"
            @change="handleUpload"
            @progress="onProgress"
          >
            <template #upload-button>
              <div
                :class="`arco-upload-list-item${file && file.status === 'error' ? ' arco-upload-list-item-error' : ''}`"
              >
                <div class="arco-upload-list-picture custom-upload-avatar" v-if="file && file.url">
                  <img :src="file.url" />
                  <div class="arco-upload-list-picture-mask">
                    <IconEdit />
                  </div>
                  <a-progress
                    v-if="file.status === 'uploading' && file.percent < 100"
                    :percent="file.percent"
                    type="circle"
                    size="mini"
                    :style="{
                      position: 'absolute',
                      left: '50%',
                      top: '50%',
                      transform: 'translateX(-50%) translateY(-50%)'
                    }"
                  />
                </div>
                <div class="arco-upload-picture-card" v-else>
                  <div class="arco-upload-picture-card-text">
                    <IconPlus />
                    <div style="margin-top: 10px; font-weight: 600">Upload</div>
                  </div>
                </div>
              </div>
            </template>
          </a-upload>
        </a-form-item>
        <a-form-item field="password" label="用户密码">
          <a-input-password v-model="form.password" placeholder="请输入密码" allow-clear />
        </a-form-item>
        <a-form-item field="confirm_password" label="确认密码">
          <a-input-password v-model="form.confirm_password" placeholder="请确认密码" allow-clear />
        </a-form-item>
      </a-form>
    </a-row>
  </a-modal>
</template>

<script setup lang="ts">
import { computed, reactive, ref } from 'vue'
import { Message, Modal, type FormInstance } from '@arco-design/web-vue'
import { IconEdit, IconPlus } from '@arco-design/web-vue/es/icon'
import { getCustomerList, uploadImage, updateCustomer } from '@/apis'

type Form = { name: string; phone: string; status: boolean }
const form: Form = reactive({
  id: '',
  nickname: '',
  remarks: '',
  headimage: '',
  password: '',
  confirm_password: ''
})

const emits = defineEmits(['reFreshTable'])
const rules = {
  name: [{ required: true, message: '请输入用户昵称' }]
}

const visible = ref(false)
const detailId = ref('')
const formRef = ref<FormInstance>()

const confirm = async () => {
  const flag = await formRef.value?.validate()
  if (flag) {
    return false
  } else {
    if (form.password != form.confirm_password) {
      Message.error('两次密码输入不一致')
      return false
    }
    const res = await updateCustomer({
      customer_id: form.id,
      headimage: form.headimage,
      nickname: form.nickname,
      remarks: form.remarks
    })
    let resData = JSON.parse(res)
    if (resData.code === 200) {
      Message.success('修改成功')
      visible.value = false
      form.id = ''
      form.password = ''
      form.confirm_password = ''
      form.headimage = ''
      file.value = null
      emits('reFreshTable')
    } else {
      Message.error(resData.message)
      return false
    }

    // return true
  }
}

const edit = (id: string) => {
  form.id = id
  initCustomer(id)
  visible.value = true
}
const initCustomer = async (id) => {
  const res = await getCustomerList({
    customer_id: id
  })
  let resData = JSON.parse(res)
  if (resData.code === 200) {
    let data = resData.result?.data?.[0] || {}
    form.id = data.id
    form.nickname = data.nickname
    form.remarks = data.remarks
    form.headimage = data.headimage
    if (form.headimage) {
      file.value = {
        url: form.headimage
      }
    }
  }
}
const file = ref()

const handleUpload = (_, currentFile) => {
  const imgUrl = import.meta.env.VITE_UPLOADED_IMAGE_BASE_URL
  // 请求上传接口
  // 上传成功后，将返回的图片地址赋值给form.headimage
  const formData = new FormData()
  formData.append('file', currentFile.file)
  uploadImage(formData).then((res) => {
    if (res.code === 200) {
      file.value = {
        ...currentFile,
        url: imgUrl + res.src
      }
      form.headimage = imgUrl + res.src
    } else {
      Message.error(res.msg)
    }
  })
}
const onProgress = (currentFile) => {
  file.value = currentFile
}

defineExpose({ edit })
</script>

<style lang="scss" scoped>
:deep(.arco-collapse-item-content) {
  background: none;
}
</style>
